package com.lib.servlet.member;

import com.alibaba.fastjson.JSON;
import com.lib.common.Constant;
import com.lib.entity.Admin;
import com.lib.entity.JsonResult;
import com.lib.service.MemberService;
import com.lib.service.ex.EmptyArgumentException;
import com.lib.service.ex.RecordIsFoundException;
import com.lib.service.ex.ServiceException;
import com.lib.service.ex.UpdateServiceException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 会员充值
 */

@WebServlet(name = "RechargeMemberServlet", value = "/admin/RechargeMemberServlet.do")
public class RechargeMemberServlet extends HttpServlet {
    private MemberService memberService = new MemberService();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Admin admin = (Admin) request.getSession().getAttribute(Constant.SESSION_ADMIN);
        String balance = request.getParameter("balance");
        String idNumber = request.getParameter("idNumber");
        JsonResult jsonResult = null;

        try {
            memberService.UpdateMemberRegdate(idNumber,balance);
            jsonResult = JsonResult.getSuccessJR();
        } catch (UpdateServiceException e) {
            jsonResult = new JsonResult(Constant.JSON_STATE_SERVICE_UPDATE,e.getMessage());
        } catch (EmptyArgumentException e) {
            jsonResult = new JsonResult(Constant.JSON_STATE_EMPTY_ARGUMENT,e.getMessage());
        } catch (RecordIsFoundException e) {
            jsonResult = new JsonResult(Constant.JSON_STATE_RECORD_IS_FOUND,e.getMessage());
        } catch (ServiceException e) {
            e.printStackTrace();
            jsonResult = new JsonResult(Constant.JSON_STATE_SERVICE_ERROR,e.getMessage());
        }
        System.out.println("----jsonResult = " + JSON.toJSONString(jsonResult));
        response.setCharacterEncoding("utf-8");
        response.getWriter().write(JSON.toJSONString(jsonResult));
        response.getWriter().flush();
        response.getWriter().close();

    }
}
